package com.flute.tools.cjf.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import com.flute.tools.cjf.entity.Char;

/**
 * ���ط���-���� ���յ���Դ�ļ��ļ��ع���
 * 
 * @author mawg
 * 
 */
public class LoadConfig {

	/**
	 * Ҫ���ص� ����-����ӳ���ļ����ļ��ĸ�ʽ��UTF-8
	 */
	public static final String fjMapUTF8 = "fj_map_utf8.properties";

	/**
	 * LoadConfig ����
	 */
	private static LoadConfig instance = null;

	/**
	 * ��ñ�����
	 * 
	 * @return
	 */
	public static LoadConfig getInstance() {
		if (instance == null) {
			instance = new LoadConfig();
		}
		return instance;
	}

	/**
	 * ���ط���-����ӳ�䣬�� Char[] ����ʽ���
	 * 
	 * @return
	 * @throws IOException
	 *             ������Դ�ļ�IO�������⣬�����ļ��е���Դ�������ݳ����쳣ʱ�׳�
	 */
	public Char[] loadFJmapUTF8() throws IOException {
		String line = null;
		ArrayList<Char> list = new ArrayList<Char>();
		BufferedReader br = null;
		Char[] charList = null;
		try {
			br = this.getReader(fjMapUTF8);
			int index = 0;
			while ((line = br.readLine()) != null) {
				if (line.startsWith("#")) {
					continue;
				}
				if (line.trim().length() == 0) {
					continue;
				}
				char fChar = line.charAt(0);
				char jChar = line.charAt(2);
				if (index >= (int) fChar) {
					list = null;
					throw new IOException("�Բ�����������ļ�[" + fjMapUTF8
							+ "]�����⣡FCharId=" + (int) fChar);
				}
				index = (int) fChar;
				list.add(new Char(jChar, fChar));
			}
			charList = new Char[list.size()];
			for (int i = 0; i < list.size(); i++) {
				charList[i] = (Char) list.get(i);
			}
			list = null;
		} catch (IOException ex) {
			list = null;
			throw ex;
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException ex) {
				}
			}
		}
		return charList;
	}

	/**
	 * ���һ������ͬĿ¼��һ���ļ���ͻ��һ��"UTF-8"�����BufferedReader
	 * 
	 * @param file
	 *            �ļ���
	 * @return BufferedReader����
	 * @throws RuntimeException
	 *             ��IO���쳣
	 */
	protected BufferedReader getReader(String file) {
		BufferedReader bufferedReader = null;
		try {
			InputStream is = LoadConfig.class.getClassLoader().getResourceAsStream(file);
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			bufferedReader = new BufferedReader(isr);
		} catch (IOException ex) {
			bufferedReader = null;
			throw new RuntimeException(ex);
		}
		return bufferedReader;
	}

}
